# -*- coding:utf-8 -*-
__author__ = 'Administrator'
__all__ = ('ButtonEnable', 'WidgetContainer', 'ButtonDiv', 'ToggleButtonDiv', )
from kivy.clock import Clock
from kivy.graphics import Rectangle, Color
from kivy.metrics import sp
from kivy.factory import Factory
from kivy.uix.widget import Widget
from kivy.properties import ListProperty,NumericProperty
from kivy.uix.behaviors.button import ButtonBehavior
from kivy.uix.behaviors.togglebutton import ToggleButtonBehavior
import os
from base import Context,Division,Content
from content import WidgetLayout

class ButtonEnable(ButtonBehavior, Context):
    pass

class WidgetContainer(Context):
    '''在composite中嵌入widget控件。把widget当content处理。
    '''
    def add_widget(self, widget, index=0, canvas=None):
        if isinstance(widget, Division):
            raise Exception('WidgetContainer can not  add division')
        if widget.parent:
            raise Exception('widget already has host parent')

        if isinstance(widget, Content):
            if self.content is not None:
                raise Exception('Context only add one content')
            self.content = widget
            if len(self.children) > 0:
                self.content.set_widget(self.children[0])
            self.add_content(widget)
            self._instruction_group.add(widget._instruction_group)
        elif isinstance(widget, Widget):
            if len(self.children) > 0:
                raise Exception('Context only add one Widget')
            self.children.append(widget)
            if self.content:
                self.content.set_widget(widget)
        widget.parent =self

    def remove_widget(self, widget):
        if not isinstance(widget,Widget):
            raise Exception('Context only remove Widget')
        if self.content:
            self.content.set_widget(None)
        widget.parent = None

class TouchDivision(Division):
    def __init__(self, **kwargs):
        #触摸事件的有效区域,touch_padding内区域触摸事件有效
        #左右上下
        self._touch_padding = (0,0,0,0)
        super(TouchDivision, self).__init__(**kwargs)
    def collide_point(self, x, y):
        left, right, top, bottom = self._touch_padding
        return (self.x + left) <= x <= (self.x + self.width - right) and (self.y + bottom) <= y <= (self.y + self.height - top)

    @property
    def touch_padding(self):
        return self._touch_padding

    @touch_padding.setter
    def touch_padding(self, value):
        if isinstance(value, tuple):
            if len(value) != 4:
                raise Exception('touch_padding must set 4 values')
            self._touch_padding = value
        else:
            self._touch_padding = (value,value,value,value)

class ButtonDiv(ButtonBehavior, TouchDivision):
    pass

class ToggleButtonDiv(ToggleButtonBehavior, TouchDivision):
    pass